﻿using System;
using System.Collections.Generic;
using System.Text;
using Cemit.PolyProto;

namespace Cemit.PolyServer
{
    /// <summary>
    /// 玩家确认的扩展方法
    /// </summary>
    public static class PlayerConfirmExtensions
    {
        private static Dictionary<string, Dictionary<string, Action>> tagActionPairs
            = new Dictionary<string, Dictionary<string, Action>>();

        /// <summary>
        /// 接收确认请求，激活该确认请求对应的委托
        /// </summary>
        public static IPlayer ReceiveConfirm(this IPlayer player, Msg_Net_Confirm msg)
        {
            if (player == null)
            {
                Debug.LogWarning("角色未登录！验证确认请求失败！");
                return player;
            }
            if (!tagActionPairs.ContainsKey(msg.Tag))
            {
                Debug.LogWarning("不存在的验证信息: " + msg.Tag);
                return player;
            }
            if (!tagActionPairs[msg.Tag].ContainsKey(player.ID))
            {
                Debug.LogWarning($"该玩家不存在该验证信息: {player.ID}-{msg.Tag}");
                return player;
            }

            tagActionPairs[msg.Tag][player.ID]?.Invoke();

            return player;
        }

        /// <summary>
        /// 向玩家发送一条确认请求，在玩家将信息原样返回后执行onPlayerConfirm，
        /// 后发送的onPlayerConfirm会替代之前发送的onPlayerConfirm
        /// TODO：超时（PingInterval时长）断开该客户端连接
        /// </summary>
        public static IPlayer SendConfirm(this IPlayer player, string tag, Action onPlayerConfirm)
        {
            try
            {
                if (!tagActionPairs.ContainsKey(tag))
                {
                    tagActionPairs.Add(tag, new Dictionary<string, Action>());
                }
            }
            catch (Exception) { }

            try
            {
                if (!tagActionPairs[tag].ContainsKey(player.ID))
                {
                    tagActionPairs[tag].Add(player.ID, onPlayerConfirm);
                    //在注销时清理该用户相关字典
                    player.OnLogout += () => tagActionPairs[tag].Remove(player.ID);
                }
            }
            catch (Exception) { }

            tagActionPairs[tag][player.ID] = onPlayerConfirm;

            player.Send(new Msg_Net_Confirm { Tag = tag });

            return player;
        }
    }
}
